import Taro from '@tarojs/taro'
import {getOpenId} from '@/api/wechat'

/**
 * 获取用户 OpenID
 * 该函数会自动处理微信登录流程并返回 openid
 *
 * @returns Promise<string> - 返回用户的 openid
 * @throws Error - 如果获取失败会抛出错误
 */
export async function getUserOpenId(): Promise<string> {
  try {
    // 1. 调用微信登录获取 code
    const loginRes = await Taro.login()
    const code = loginRes.code

    if (!code) {
      throw new Error('获取登录凭证失败')
    }

    // 2. 使用 code 换取 openid
    const result = await getOpenId(code)

    if (!result.success) {
      throw new Error(result.error || '获取 OpenID 失败')
    }

    const openid = result.data.openid

    if (!openid) {
      throw new Error('OpenID 为空')
    }

    return openid
  } catch (error) {
    console.error('获取 OpenID 失败:', error)
    throw error
  }
}

/**
 * 获取用户 OpenID（带缓存）
 * 该函数会将 openid 缓存到本地存储，避免频繁调用接口
 *
 * @param forceRefresh - 是否强制刷新，默认 false
 * @returns Promise<string> - 返回用户的 openid
 */
export async function getCachedOpenId(forceRefresh = false): Promise<string> {
  const CACHE_KEY = 'user_openid'
  const CACHE_EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000 // 7天过期

  try {
    // 如果不强制刷新，先尝试从缓存读取
    if (!forceRefresh) {
      const cachedData = Taro.getStorageSync(CACHE_KEY)
      if (cachedData) {
        const {openid, timestamp} = JSON.parse(cachedData)
        const now = Date.now()

        // 检查缓存是否过期
        if (openid && timestamp && now - timestamp < CACHE_EXPIRE_TIME) {
          return openid
        }
      }
    }

    // 获取新的 openid
    const openid = await getUserOpenId()

    // 缓存到本地存储
    Taro.setStorageSync(
      CACHE_KEY,
      JSON.stringify({
        openid,
        timestamp: Date.now()
      })
    )

    return openid
  } catch (error) {
    console.error('获取缓存的 OpenID 失败:', error)
    throw error
  }
}

/**
 * 清除 OpenID 缓存
 */
export function clearOpenIdCache() {
  const CACHE_KEY = 'user_openid'
  try {
    Taro.removeStorageSync(CACHE_KEY)
  } catch (error) {
    console.error('清除 OpenID 缓存失败:', error)
  }
}
